package com.css.fxfzfxqh.modules.buildingKilometerGrid.service;

import cn.hutool.core.util.PageUtil;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.base.response.RestResponse;
import com.css.fxfzfxqh.common.rest.JcsjRestManager;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.model.entity.*;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.model.vo.BuildGridFindAllVo;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.model.vo.ListGridDataByVersionCodeVo;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.repository.FxqhBuildingGridRepository;
import com.css.fxfzfxqh.modules.largeScreen.entity.BuildingVO;
import com.css.fxfzfxqh.util.PlatformObjectUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.security.provider.certpath.OCSPResponse;

import java.util.*;
import java.util.concurrent.*;

/**
 * 建筑物公里网格service
 */
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class FxqhBuildingGridService {

    @Autowired
    private FxqhBuildingGridRepository fxqhBuildingGridRepository;
    @Autowired
    private FxqhBuildingGridUrbanOtherService fxqhBuildingGridUrbanOtherService;
    @Autowired
    private FxqhBuildingGridUrbanSteelService fxqhBuildingGridUrbanSteelService;
    @Autowired
    private FxqhBuildingGridUrbanSteelConcreteService fxqhBuildingGridUrbanSteelConcreteService;
    @Autowired
    private FxqhBuildingGridUrbanWoodService fxqhBuildingGridUrbanWoodService;
    @Autowired
    private FxqhBuildingGridUrbanMasonryService fxqhBuildingGridUrbanMasonryService;
    @Autowired
    private FxqhBuildingGridRuralWoodBambooService fxqhBuildingGridRuralWoodBambooService;
    @Autowired
    private FxqhBuildingGridRuralSteelService fxqhBuildingGridRuralSteelService;
    @Autowired
    private FxqhBuildingGridRuralSteelConcreteService fxqhBuildingGridRuralSteelConcreteService;
    @Autowired
    private FxqhBuildingGridRuralOtherService fxqhBuildingGridRuralOtherService;
    @Autowired
    private FxqhBuildingGridRuralMixedService fxqhBuildingGridRuralMixedService;
    @Autowired
    private FxqhBuildingGridRuralMasonryService fxqhBuildingGridRuralMasonryService;
    @Autowired
    private FxqhBuildingGridRuralCivilService fxqhBuildingGridRuralCivilService;
    @Autowired
    private FxqhBuildingGridRuralBottomFrameService fxqhBuildingGridRuralBottomFrameService;
    @Autowired
    JcsjRestManager jcsjRestManager;
    public static final String[] tables = {
            "fxqh_building_grid_rural_bottom_frame",
            "fxqh_building_grid_rural_civil",
            "fxqh_building_grid_rural_masonry",
            "fxqh_building_grid_rural_mixed",
            "fxqh_building_grid_rural_other",
            "fxqh_building_grid_rural_steel",
            "fxqh_building_grid_rural_steel_concrete",
            "fxqh_building_grid_rural_wood_bamboo",
            "fxqh_building_grid_urban_masonry",
            "fxqh_building_grid_urban_other",
            "fxqh_building_grid_urban_steel",
            "fxqh_building_grid_urban_steel_concrete",
            "fxqh_building_grid_urban_wood",
    };

    public Map<String, List<BuildGridFindAllVo>> findBuildGridFindAllVo() {
        Map<String, List<BuildGridFindAllVo>> map = new HashMap<>();
        map.put("rural_bottom_frame", fxqhBuildingGridRepository.findAll("fxqh_building_grid_rural_bottom_frame", BuildGridFindAllVo.class));
        map.put("rural_civil", fxqhBuildingGridRepository.findAll("fxqh_building_grid_rural_civil", BuildGridFindAllVo.class));
        map.put("rural_masonry", fxqhBuildingGridRepository.findAll("fxqh_building_grid_rural_masonry", BuildGridFindAllVo.class));
        map.put("rural_mixed", fxqhBuildingGridRepository.findAll("fxqh_building_grid_rural_mixed", BuildGridFindAllVo.class));
        map.put("rural_other", fxqhBuildingGridRepository.findAll("fxqh_building_grid_rural_other", BuildGridFindAllVo.class));
        map.put("rural_steel", fxqhBuildingGridRepository.findAll("fxqh_building_grid_rural_steel", BuildGridFindAllVo.class));
        map.put("rural_steel_concrete", fxqhBuildingGridRepository.findAll("fxqh_building_grid_rural_steel_concrete", BuildGridFindAllVo.class));
        map.put("rural_wood_bamboo", fxqhBuildingGridRepository.findAll("fxqh_building_grid_rural_wood_bamboo", BuildGridFindAllVo.class));
        map.put("urban_masonry", fxqhBuildingGridRepository.findAll("fxqh_building_grid_urban_masonry", BuildGridFindAllVo.class));
        map.put("urban_other", fxqhBuildingGridRepository.findAll("fxqh_building_grid_urban_other", BuildGridFindAllVo.class));
        map.put("urban_steel", fxqhBuildingGridRepository.findAll("fxqh_building_grid_urban_steel", BuildGridFindAllVo.class));
        map.put("urban_steel_concrete", fxqhBuildingGridRepository.findAll("fxqh_building_grid_urban_steel_concrete", BuildGridFindAllVo.class));
        map.put("urban_wood", fxqhBuildingGridRepository.findAll("fxqh_building_grid_urban_wood", BuildGridFindAllVo.class));
        return map;
    }

    public void delBuildingGridTempDatas() {
        for (String table : tables) {
            fxqhBuildingGridRepository.delBuildingGridTempDatas(table);
        }
    }


//    /**
//     * 查询中心点
//     *
//     * @param id
//     * @param table
//     * @return
//     */
//    public String selectCenterPointById(String id, String table) {
//        return fxqhBuildingGridRepository.selectCenterPoint(id, table);
//    }

    /**
     * 查询中心点
     *
     * @param geom
     * @return
     */
    public String selectCenterPointByGeom(String geom) {
        return fxqhBuildingGridRepository.selectCenterPoint(geom);
    }

    @Transactional()
    public void saveParseData(String sourceVersionCode, String targetVersionCode) {
        for (String table : tables) {
            fxqhBuildingGridRepository.changeTempToRealData(table, sourceVersionCode, targetVersionCode);
        }
//        BizThreadPoolManage.exeBizThreadPoolExecutor.execute(() -> {
//            for (String table : tables) {
//                List<GridSelectByVersionCodeDto> list = fxqhBuildingGridRepository.selectByVersionCode(targetVersionCode, table);
//                for (GridSelectByVersionCodeDto gridSelectByVersionCodeDto : list) {
//                    try {
//                        GetChinaGridBo chinaGridIdNew = jcsjRestManager.getChinaGridIdNew(gridSelectByVersionCodeDto.getGeom(), gridSelectByVersionCodeDto.getProvince(), gridSelectByVersionCodeDto.getCity(), gridSelectByVersionCodeDto.getCounty());
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        log.warn("id:{},保存格网id失败", gridSelectByVersionCodeDto.getId());
//                        log.error(e.getMessage(), e);
//                    }
//                }
//            }
//        });
//        try {
//            ExecutorService service = Executors.newFixedThreadPool(tables.length);
//            List<Future> futureList = new ArrayList<>();
//            log.info("开始-----------------------");
//            for (String table : tables) {
//                    List<GridSelectByVersionCodeDto> list = fxqhBuildingGridRepository.selectByVersionCode(targetVersionCode, table);
//                    for (GridSelectByVersionCodeDto gridSelectByVersionCodeDto : list) {
//                         BizThreadPoolManage.exeBizThreadPoolExecutor.execute(() -> {
//                        try {
//                            GetChinaGridBo chinaGridIdNew = jcsjRestManager.getChinaGridIdNew(gridSelectByVersionCodeDto.getGeom(), gridSelectByVersionCodeDto.getProvince(), gridSelectByVersionCodeDto.getCity(), gridSelectByVersionCodeDto.getCounty());
//                            if (chinaGridIdNew.getCode() == 200) {
////                                Callable callable = new ReloadCallable(chinaGridIdNew.getData(), gridSelectByVersionCodeDto.getId(),table);
////                                Future submit = service.submit(callable);
////                                futureList.add(submit);
//                                 fxqhBuildingGridRepository.updateExtends1ById(chinaGridIdNew.getData(), gridSelectByVersionCodeDto.getId(), table);
//                                log.debug("id:{},保存格网id成功", gridSelectByVersionCodeDto.getId());
//                            } else {
//                                log.warn("id:{},保存格网id失败", gridSelectByVersionCodeDto.getId());
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            log.warn("id:{},保存格网id失败", gridSelectByVersionCodeDto.getId());
//                            log.error(e.getMessage(), e);
//                        }
//                         });
//                    }
//            }
////            //不在接收新的任务
////            service.shutdown();
////            // 等待所有线程执行完毕
////            service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
////            for (Future future : futureList) {
////                String[] strings = (String[])future.get();
////                fxqhBuildingGridRepository.updateExtends1ById(strings[0], strings[1], strings[2]);
////            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            // log.warn("id:{},保存格网id失败", gridSelectByVersionCodeDto.getId());
//            log.error(e.getMessage(), e);
//        }
    }

    public RestResponse getBuildingCategoryStatistics(String code) {
        List<BuildingVO> buildingCategoryStatistics = fxqhBuildingGridRepository.getBuildingCategoryStatistics(code);
        try {
            if(PlatformObjectUtils.isEmpty(buildingCategoryStatistics) || buildingCategoryStatistics.size()==0){
                return RestResponse.fail(500,"查询不到数据");
            }
            return RestResponse.succeed(new HashMap<String, Object>() {{
                put("data", buildingCategoryStatistics);
                put("message", "");
            }});
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(500,"查询不到数据");
        }
    }

    static class ReloadCallable implements Callable<Object> {
        private String extend1;
        private String id;
        private String table;

        ReloadCallable(String extend1, String id, String table) {
            this.extend1 = extend1;
            this.id = id;
            this.table = table;
        }

        @Override
        public Object call() throws Exception {
            String[] stringsMap = new String[]{extend1, id, table};

            return stringsMap;
        }
    }

    public void delByVersionCode(String versionCode, Date currTime, String currUid) {
        for (String table : tables) {
            fxqhBuildingGridRepository.delByVersionCode(table, versionCode, currTime, currUid);
        }
    }

    public ListGridDataByVersionCodeVo listGridDataByVersionCode(String version) {
        List<FxqhBuildingGridUrbanOther> fxqhBuildingGridUrbanOthers = fxqhBuildingGridUrbanOtherService.listGridDataByVersionCode(version);
        List<FxqhBuildingGridUrbanSteel> fxqhBuildingGridUrbanSteels = fxqhBuildingGridUrbanSteelService.listGridDataByVersionCode(version);
        List<FxqhBuildingGridUrbanSteelConcrete> fxqhBuildingGridUrbanSteelConcretes = fxqhBuildingGridUrbanSteelConcreteService.listGridDataByVersionCode(version);
        List<FxqhBuildingGridUrbanWood> fxqhBuildingGridUrbanWoods = fxqhBuildingGridUrbanWoodService.listGridDataByVersionCode(version);
        List<FxqhBuildingGridUrbanMasonry> fxqhBuildingGridUrbanMasonries = fxqhBuildingGridUrbanMasonryService.listGridDataByVersionCode(version);
        List<FxqhBuildingGridRuralWoodBamboo> fxqhBuildingGridRuralWoodBamboos = fxqhBuildingGridRuralWoodBambooService.listGridDataByVersionCode(version);
        List<FxqhBuildingGridRuralSteel> fxqhBuildingGridRuralSteels = fxqhBuildingGridRuralSteelService.listGridDataByVersionCode(version);
        List<FxqhBuildingGridRuralSteelConcrete> fxqhBuildingGridRuralSteelConcretes = fxqhBuildingGridRuralSteelConcreteService.listGridDataByVersionCode(version);
        List<FxqhBuildingGridRuralOther> fxqhBuildingGridRuralOthers = fxqhBuildingGridRuralOtherService.listGridDataByVersionCode(version);
        List<FxqhBuildingGridRuralMixed> fxqhBuildingGridRuralMixeds = fxqhBuildingGridRuralMixedService.listGridDataByVersionCode(version);
        List<FxqhBuildingGridRuralMasonry> fxqhBuildingGridRuralMasonries = fxqhBuildingGridRuralMasonryService.listGridDataByVersionCode(version);
        List<FxqhBuildingGridRuralCivil> fxqhBuildingGridRuralCivils = fxqhBuildingGridRuralCivilService.listGridDataByVersionCode(version);
        List<FxqhBuildingGridRuralBottomFrame> fxqhBuildingGridRuralBottomFrames = fxqhBuildingGridRuralBottomFrameService.listGridDataByVersionCode(version);
        ListGridDataByVersionCodeVo vo = new ListGridDataByVersionCodeVo();
        vo.setFxqhBuildingGridUrbanOthers(fxqhBuildingGridUrbanOthers);
        vo.setFxqhBuildingGridUrbanSteels(fxqhBuildingGridUrbanSteels);
        vo.setFxqhBuildingGridUrbanSteelConcretes(fxqhBuildingGridUrbanSteelConcretes);
        vo.setFxqhBuildingGridUrbanWoods(fxqhBuildingGridUrbanWoods);
        vo.setFxqhBuildingGridUrbanMasonries(fxqhBuildingGridUrbanMasonries);
        vo.setFxqhBuildingGridRuralWoodBamboos(fxqhBuildingGridRuralWoodBamboos);
        vo.setFxqhBuildingGridRuralSteels(fxqhBuildingGridRuralSteels);
        vo.setFxqhBuildingGridRuralSteelConcretes(fxqhBuildingGridRuralSteelConcretes);
        vo.setFxqhBuildingGridRuralOthers(fxqhBuildingGridRuralOthers);
        vo.setFxqhBuildingGridRuralMixeds(fxqhBuildingGridRuralMixeds);
        vo.setFxqhBuildingGridRuralMasonries(fxqhBuildingGridRuralMasonries);
        vo.setFxqhBuildingGridRuralCivils(fxqhBuildingGridRuralCivils);
        vo.setFxqhBuildingGridRuralBottomFrames(fxqhBuildingGridRuralBottomFrames);
        return vo;
    }
}
